package com.zg.invoice.dao;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.zg.common.core.dao.BaseEntity;
import com.zg.invoice.vo.InvoiceCallBack;
import com.zg.invoice.vo.OpenInvoiceDetails;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @TableName JS_INVOICE_OPEN
 */
@Data
@Accessors(chain = true)
@Slf4j
public class JsInvoiceOpen  extends BaseEntity {
    /**
     *
     */
//    @JsonFormat(shape = JsonFormat.Shape.STRING)//转化成string传到前端
//    private Long id;

    /**
     * 结算单号
     */
    private String settlementNo;

    /**
     * 发票类型 1专票,2普票,3电票,4数电纸票
     */
    private Long invoiceType;

    /**
     * 发票状态:10.正常20.已被红冲.30.已被作废 40:等待处理结果
     */
    private Long invoiceStatus;

    /**
     * 开票类型 0 正数 1 红冲
     */
    private Long billingType;

    /**
     * 打印状态 0:未打印.1:已打印
     */
    private Long printStatus;

    /**
     * 发票代码
     */
    private String invoiceCode;

    /**
     * 发票号码

     */
    private String invoiceNo;

    /**
     * 销方名称
     */
    private String sellerName;

    /**
     * 销方税号
     */
    private String sellerTaxNo;

    /**
     * 销方地址
     */
    private String sellerAddress;

    /**
     * 销方电话
     */
    private String sellerTel;

    /**
     * 销方银行名称
     */
    private String sellerBankName;

    /**
     * 销方银行账号
     */
    private String sellerBankAccount;

    /**
     * 购方名称
     */
    private String purchaserName;

    /**
     * 购方税号
     */
    private String purchaserTaxNo;

    /**
     * 购方地址
     */
    private String purchaserAddress;

    /**
     * 购方电话
     */
    private String purchaserTel;

    /**
     * 购方银行名称
     */
    private String purchaserBankName;

    /**
     * 购方银行账号
     */
    private String purchaserBankAccount;

    /**
     * 购方代码
     */
    private String purchaserCode;

    /**
     * 购方邮箱
     */
    private String purchaserEmail;

    /**
     * 收款人
     */
    private String payee;

    /**
     * 复核人
     */
    private String reviewer;

    /**
     * 开票人
     */
    private String drawer;

    /**
     * 机器编码
     */
    private String machineCode;

    /**
     * 开票机号
     */
    private String machineNo;

    /**
     * 不含税金额
     */
    private BigDecimal amount;

    /**
     * 含税金额
     */
    private String amountWithTax;

    /**
     * 税额
     */
    private String taxAmount;

    /**
     * 校验码
     */
    private String checkCode;

    /**
     * 开票日期
     */
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date drewDate;

    @TableField(exist = false)
    private String drewDateStr;

    /**
     * 通知单编号
     */
    private String redApplicationNo;

    /**
     * 税控码
     */
    private String taxCode;

    /**
     * 备注
     */
    private String remark;

    /**
     * 密文
     */
    private String ciphertext;

    /**
     * 0 预制发票 1 订单开票 2 发票填开 3 发票修复
     */
    private Long invoiceSourceModule;

    /**
     * 清单标识 0 非清单 1 清 单
     */
    private Long listFlag;

    /**
     * 0 自取 1 物流
     */
    private Long logisticsFlag;

    /**
     * 税率
     */
    private String taxRate;

    /**
     * 作废理由
     */
    private String cancelReason;

    /**
     * 作废日期
     */
    private Date cancelTime;

    /**
     * 电票url
     */
    private String pdfUrl;

    /**
     * ofd url
     */
    private String ofdUrl;

    /**
     * 电票预览地址
     */
    private String viewUrl;



    /**
     * 红冲时使用 原蓝票号码
     */
    @TableField(exist = false)
    private String oldInvoiceNo;

    /**
     * 红冲时使用 原蓝票号码
     */
    @TableField(exist = false)
    private String oldInvoiceCode;


    /**
     * 外部单据号（订单号）
     */
    private String externalDocumentNo;


    /**
     * 发票明细
     */
    @TableField(exist = false)
    private List<JsInvoiceOpenDetail> detailList;

    /**
     * xmlUrl
     */
    private String xmlUrl;

    /**
     * 关联上级发票号码
     */
    private String parentInvoiceNo;

    /**
     * 每千克煤炭发热量（千卡）
     */
    private String mtrl;
    /**
     * 干基全硫（%）
     */
    private String mtql;
    /**
     * 干燥无灰基挥发分（%）
     */
    private String mthf;

    private static final long serialVersionUID = 1L;


    public static JsInvoiceOpen toJsInvoiceOpen(InvoiceCallBack callBack){
        JsInvoiceOpen jsInvoiceOpen = new JsInvoiceOpen();

        //外部单据号，订单号
        jsInvoiceOpen.setExternalDocumentNo(callBack.getOrderNo());
        //结算单号
        jsInvoiceOpen.setSettlementNo(callBack.getInvoiceId());
        //发票类型 发票类型 1专票,2普票,3电票,4数电纸票
        //数电票没有发票代码
        if ("bs".equals(callBack.getInvoiceLine())) {
            jsInvoiceOpen.setInvoiceType(3L);
        }else if ("es".equals(callBack.getInvoiceLine())) {
            jsInvoiceOpen.setInvoiceType(4L);
        }else {
            jsInvoiceOpen.setInvoiceType(1L);
        }

        //发票状态  发票状态:10.正常20.已被红冲.30.已被作废
        jsInvoiceOpen.setInvoiceStatus(10L);
        //诺诺，开票类型，1:蓝票；2:红票
        if(ObjectUtil.isNotEmpty(callBack.getInvoiceType()) && 1 == callBack.getInvoiceType()){
            //开票类型 开票类型 0 正数 1 红冲
            jsInvoiceOpen.setBillingType(0L);
        }
        if(ObjectUtil.isNotEmpty(callBack.getInvoiceType()) && 2 == callBack.getInvoiceType()){
            //开票类型 开票类型 0 正数 1 红冲
            jsInvoiceOpen.setBillingType(1L);
        }
        //打印状态
        //发票代码
        jsInvoiceOpen.setInvoiceCode(callBack.getInvoiceCode());
        //发票号码
        jsInvoiceOpen.setInvoiceNo(callBack.getInvoiceNumber());
        //销方名称
        jsInvoiceOpen.setSellerName(callBack.getSellerName());
        //销方税号
        jsInvoiceOpen.setSellerTaxNo(callBack.getSellerTaxnum());
        //销方地址+电话
        jsInvoiceOpen.setSellerAddress(callBack.getSellerAddress()+" "+callBack.getSellerPhone());
        //销方电话
        jsInvoiceOpen.setSellerTel(callBack.getSellerPhone());
        //销方银行名称+账号
        jsInvoiceOpen.setSellerBankName(callBack.getSellerBank()+" "+callBack.getSellerAccount());
        //销方银行账号
        jsInvoiceOpen.setSellerBankAccount(callBack.getSellerAccount());
        //购方名称
        jsInvoiceOpen.setPurchaserName(callBack.getBuyerName());
        //购方税号
        jsInvoiceOpen.setPurchaserTaxNo(callBack.getBuyerTaxnum());
        //购方地址+电话
        jsInvoiceOpen.setPurchaserAddress(callBack.getBuyerAddress()+" "+callBack.getBuyerPhone());
        //购方电话
        jsInvoiceOpen.setPurchaserTel(callBack.getBuyerPhone());
        //购方银行名称+账号
        jsInvoiceOpen.setPurchaserBankName(callBack.getBuyerBank()+" "+callBack.getBuyerAccount());
        //购方银行账号
        jsInvoiceOpen.setPurchaserBankAccount(callBack.getBuyerAccount());
        //购方代码

        //购方邮箱

        //收款人
        jsInvoiceOpen.setPayee(callBack.getPayee());
        //复核人
        jsInvoiceOpen.setReviewer(callBack.getChecker());
        //开票人
        jsInvoiceOpen.setDrawer(callBack.getClerker());
        //机器编码
        jsInvoiceOpen.setMachineCode(callBack.getMachineNumber());
        //开票机号
        jsInvoiceOpen.setMachineNo(String.valueOf(callBack.getExtensionNum()));
        //不含税金额
        jsInvoiceOpen.setAmount(callBack.getTaxFreeAmountTotal());
        //含税金额
        jsInvoiceOpen.setAmountWithTax(String.valueOf(callBack.getTaxAmountTotal()));
        //税额
        jsInvoiceOpen.setTaxAmount(String.valueOf(callBack.getTaxTotal()));
        //校验码
        jsInvoiceOpen.setCheckCode(callBack.getCheckCode());
        //开票日期
        jsInvoiceOpen.setDrewDate(callBack.getInvoiceTime());
        //通知单编号
        //税控码
        jsInvoiceOpen.setTaxCode(callBack.getMachineNumber());
        //备注
        jsInvoiceOpen.setRemark(callBack.getRemark());
        //密文
        jsInvoiceOpen.setCiphertext(callBack.getInvoiceCipher());
        //0 预制发票 1 订单开票 2 发票填开 3 发票修复
        //清单标识
        jsInvoiceOpen.setListFlag(ObjectUtils.isNotEmpty(callBack.getListFlag()) ? Long.valueOf(callBack.getListFlag()) : null);
        //0 自取 1 物流
        //税率
        jsInvoiceOpen.setTaxRate(ObjectUtil.isNotEmpty(callBack.getDetail()) ? callBack.getDetail().get(0).getTaxrate() : "");
        //作废理由
        jsInvoiceOpen.setCancelReason(String.valueOf(callBack.getInvalidReason()));
        //作废日期
        jsInvoiceOpen.setCancelTime(callBack.getInvalidTime());
        //电票url
        jsInvoiceOpen.setPdfUrl(callBack.getPdfUrl());
        //ofd url
        jsInvoiceOpen.setOfdUrl(callBack.getOfdUrl());
        //xml url
        jsInvoiceOpen.setXmlUrl(callBack.getXmlUrl());
        //电票预览地址
        if (ObjectUtils.isNotEmpty(callBack.getCreateTime())){
            //创建时间
            jsInvoiceOpen.setCreateTime(Timestamp.from(Instant.ofEpochMilli(callBack.getCreateTime().getTime())));
        }
        if (ObjectUtils.isNotEmpty(callBack.getUpdateTime())){
            //修改时间
            jsInvoiceOpen.setUpdateTime(Timestamp.from(Instant.ofEpochMilli(callBack.getUpdateTime().getTime())));
        }
        //红冲时使用 原蓝票号码
        jsInvoiceOpen.setOldInvoiceNo(callBack.getOriInvoiceNumber());
        //红冲时使用 原蓝票代码
        jsInvoiceOpen.setOldInvoiceCode(callBack.getOriInvoiceCode());
        //机构id
        //环节实例编码
        //下一环节编号
        //下一环节处理人
        //发票明细
        List<OpenInvoiceDetails> resDetailList = callBack.getDetail();
        ArrayList<JsInvoiceOpenDetail> toJsDetailList = new ArrayList<>();
        JsInvoiceOpenDetail jsInvoiceOpenDetail;
        if (ObjectUtils.isNotEmpty(callBack.getErrorMessage()) && ObjectUtils.isEmpty(resDetailList)) {
            log.error("诺税通回调返回信息：" + callBack.getErrorMessage());
            return jsInvoiceOpen;
        }
        for (OpenInvoiceDetails openInvoiceDetails: resDetailList) {
            jsInvoiceOpenDetail = new JsInvoiceOpenDetail();
            //含税金额
            jsInvoiceOpenDetail.setAmountWithTax(openInvoiceDetails.getTaxAmount());
            //商品名称
            jsInvoiceOpenDetail.setGoodsName(openInvoiceDetails.getGoodsName());
            //税收分类编码
            jsInvoiceOpenDetail.setRevenueCode(openInvoiceDetails.getGoodsCode());
            //简称
            jsInvoiceOpenDetail.setShortName(openInvoiceDetails.getGoodsCodeAbb());
            //规格
            jsInvoiceOpenDetail.setSpecification(openInvoiceDetails.getSpecType());
            //是否享受优惠政策
            jsInvoiceOpenDetail.setTaxPre(Long.valueOf(openInvoiceDetails.getFavouredPolicyFlag()));
            //优惠政策类型,诺税通无返回该字段
            jsInvoiceOpenDetail.setTaxPreType(2L);
            //税率
            jsInvoiceOpenDetail.setTaxRate(new BigDecimal(openInvoiceDetails.getTaxrate()));
            //单价含税标识
            jsInvoiceOpenDetail.setTaxSign(ObjectUtil.isNotEmpty(openInvoiceDetails.getWithTaxFlag()) ? Long.valueOf(openInvoiceDetails.getWithTaxFlag()) : null);
            //单位
            jsInvoiceOpenDetail.setUnit(openInvoiceDetails.getGoodsUnit());
            //单价
            jsInvoiceOpenDetail.setUnitPrice(openInvoiceDetails.getGoodsPrice());
            //税额
            jsInvoiceOpenDetail.setTaxAmount(openInvoiceDetails.getTax());
            //不含税金额
            jsInvoiceOpenDetail.setAmount(openInvoiceDetails.getTaxFreeAmount());
            //数量
            jsInvoiceOpenDetail.setQuantity(String.valueOf(openInvoiceDetails.getGoodsNum()));
            toJsDetailList.add(jsInvoiceOpenDetail);
        }
        jsInvoiceOpen.setDetailList(toJsDetailList);
        return jsInvoiceOpen;
    }
}
